<!DOCTYPE html>
<html>
 
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
  <meta name="keywords" content="">
  <meta name="description" content="">
  <meta name="format-detection" content="telephone=no" />
  <!-- new end -->
  <style>
      #myCanvas{
        letter-spacing: 2px;
      }
  </style>
</head>
 
<body>
  <div class="mui-content">
    <!-- <button onclick="mmm('wrap-img','inner-img')" type="button" class="mui-btn mui-btn-blue mui-btn-block">按钮</button> -->
    <!-- <img id="inner-img" src="/img/2.png" /> -->
    <!-- 
        这里要注意 同源策略
        可以用自己服务器上的图片
        如果遇到问题 请去Stack Overflow解决相关问题
     -->
    <img id="wrap-img" src="/img/1.png" style='display:none'/>
    <canvas id="myCanvas" width="270" height="135" style="border:1px solid #d3d3d3;">
    </canvas>
    <img src="" alt="" id='new-img'>
  </div>
  <script src='https://benjazhu-1.oss-cn-shenzhen.aliyuncs.com/assets/js/jquery2.1.5.min.js'></script>
  <script> </script>
  <script>
    //两张图
    // var img = document.getElementById('wrap-img');
    var img = new Image();
    img.src = './img/1.png'
    var canvas = document.getElementById("myCanvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    ctx.font = "700 36px 'Noto Sans',sans-serif";
    ctx.fillStyle = "#fff";
    ctx.fillText("100100123456写下", 718, 113);
    srccc = canvas.toDataURL("image/jpeg", 0.8);
    console.log(srccc);

    let str='数据交互上海耳朵接口欧式恰饭饿含防腐剂冃由于钱数据交互上海耳朵接口欧式恰饭饿含防腐剂冃由于钱数据交互上海耳朵接口欧式恰饭饿含防腐剂冃由于钱数据交互上海耳朵接口欧式恰饭饿含防腐剂冃由于钱数据交互上海耳朵接口欧式恰饭饿含防腐剂冃由于钱'
    console.log(str.length,'length');
    let canvasWidth = 410;//计算canvas的宽度
    let initHeight= 190;//绘制的文字距离canvas顶部初始的高度
    let lineWidth = 0;
    let StrIndex= 0; //每次开始截取的字符串的索引
    ctx.fillStyle = "#000";
    ctx.font = "400 36px 'Noto Sans '";
    for(let i=0;i<str.length;i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(StrIndex, i), 692, initHeight);//绘制截取部分
        initHeight += 42;//这里22为字体的高度
        lineWidth = 0;
        StrIndex = i;
      }
      if (i == str.length - 1) {//绘制剩余部分
        ctx.fillText(str.substring(StrIndex, i + 1), 692, initHeight);
      }
    }

    $('#new-img').attr('src', srccc);

  </script>
</body>
 
</html>
